package service

import (
	"awesomeProject2/global"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strings"
)

func FillTeacher(teacher *model.Teacher, requestInfo *request.TeacherInfo) {
	utils.StructAssign(teacher, requestInfo)
	// 将request中的list数据转换成paper中的str
	teacher.TeacherType = strings.Join(requestInfo.TeacherTypeList, ",")
	teacher.MajorName = strings.Join(requestInfo.MajorNameList, ",")
	teacher.ResearchDirection = strings.Join(requestInfo.ResearchDirectionList, ",")
}

func Login(u *model.User) (err error, userInter *model.User) {
	u.Password = utils.MD5V([]byte(u.Password))
	err, user := model.GetUserByDynamicQuery(u)

	isNotFound := errors.Is(err, gorm.ErrRecordNotFound)
	if isNotFound {
		return utils.BusinessError{Code: utils.ERROR_PASSWORD_WRONG}, nil
	}
	return err, &user
}

func ChangePasswd(id uint, passwd string) error {
	password := utils.MD5V([]byte(passwd))
	err := global.GVA_DB.Model(&model.User{}).Where("id = ?", id).Update("password", password).Error
	return err
}

func UpdateTeacher(c *gin.Context, teacher *model.Teacher) (err error) {
	var id uint

	if id, err = model.GetCurrentTeacherId(c); err != nil {
		return err
	}

	if teacher.ID != id {
		return utils.BusinessError{Code: utils.ERROR_ABNORMAL_PERMISSIONS}
	}

	return model.UpdateTeacher(teacher)
}
